package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.GwEnterpriseInfo;
import com.ruoyi.system.domain.GwPlatformAccount;
import com.ruoyi.system.domain.GwSystemConfig;
import com.ruoyi.system.domain.vo.AppletLoginVO;
import com.ruoyi.system.mapper.GwSystemConfigMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService extends BaseService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private IGwPlatformAccountService platformAccountService;

    @Resource
    private WeChatUtil weChatUtil;
    @Autowired
    private IGwEnterpriseInfoService gwEnterpriseInfoService;
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private GwSystemConfigMapper systemConfigMapper;
    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private ISysUserService iSysUserService;

    @Value("${wechat.loginCallBackUrl}")
    private String loginCallBackUrl;
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.pcAppId}")
    private String pcAppId;
    @Value("${wechat.pcSecret}")
    private String pcSecret;


    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        loginUser.setEnterpriseId(getUserEnterpriseId(loginUser));
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * @Author haiyue
     * @Description 查询登录人所在企业id，没企业返回空
     * @Date 上午 10:19:10 2025/5/26
     * @param loginUser
     * @return 企业id
     **/
    private String getUserEnterpriseId(LoginUser loginUser) {
        if(loginUser.getUser()!=null){
            String userType = loginUser.getUser().getUserType();

            if(userType.equals(UserType.SYSTEM_USER.getCode())|| userType.equals(UserType.OPERATION_USER.getCode())
            ||  userType.equals(UserType.AGENT_USER.getCode())){
            return null;
            }
            if(userType.equals(UserType.PLATFORM_USER.getCode()) && !StringUtils.isEmpty(loginUser.getUser().getChannelId())){
                GwPlatformAccount account = platformAccountService.selectGwPlatformAccountById(loginUser.getUser().getChannelId());
                return account!=null?account.getEnterpriseId():null;
            }else if(userType.equals(UserType.ENTERPRISE_USER.getCode()) && !StringUtils.isEmpty(loginUser.getUser().getChannelId())){
                return loginUser.getUser().getChannelId();
            }

        }
        return null;
    }


    public AjaxResult appletLogin(AppletLoginVO appletLoginVO)
    {
        if(appletLoginVO==null || StringUtils.isEmpty(appletLoginVO.getJsCode()) || StringUtils.isEmpty(appletLoginVO.getPhoneCode())){
            return AjaxResult.error("缺少必要参数，无法登录");
        }

        //1、获取调接口凭证
        String accessToken = weChatUtil.getAccessToken();
        if(StringUtils.isEmpty(accessToken)){
            return AjaxResult.error("系统异常，微信接口凭证获取失败！");
        }
        //2、调用登录接口获取openId
        Map<String,String> map = weChatUtil.codeSession(appletLoginVO.getJsCode());
        if(map==null){
            return AjaxResult.error("系统异常，微信登录失败！");
        }
        if(StringUtils.isNotEmpty(map.get("result")) && map.get("result").equals("fail")){
            return AjaxResult.error("微信登录失败，错误码【"+map.get("errcode")+"】"+map.get("errmsg"));
        }

        String openId = map.get("openid");
        String sessionKey= map.get("sessionKey");
        //将sessionKey缓存5分钟,便于后面使用
        redisCache.setCacheObject(openId,sessionKey,5, TimeUnit.MINUTES);

        //解密手机号
        String phoneNumber = weChatUtil.getPhoneNumber(appletLoginVO.getPhoneCode());
        if(StringUtils.isEmpty(phoneNumber)){
            return AjaxResult.error("手机号解密失败，稍后再试！");
        }
        //判断手机号是否注册过
        if(checkPhone(phoneNumber)){
            //查询试用天数
            //查询系统配置
            List<GwSystemConfig> configList = systemConfigMapper.selectGwSystemConfigList(new GwSystemConfig());
            Long days = 7L;
            if(!CollectionUtils.isEmpty(configList)){
                GwSystemConfig config = configList.get(0);
                days=config.getTryDays();
            }
            return AjaxResult.error(230,String.valueOf(days));
        }


        AjaxResult ajax = new AjaxResult();
        SysUser user = userService.selectUserByPhone(phoneNumber);
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUser(user);

        if((StringUtils.isEmpty(user.getOpenId()) || !openId.equals(user.getOpenId()))){
            user.setOpenId(openId);
            sysUserMapper.updateUser(user);
        }

        // 权限集合
        Set<String> permissions = permissionService.getAppletMenuPermission(user);
//        if (!loginUser.getPermissions().equals(permissions))
//        {
//            loginUser.setPermissions(permissions);
//            tokenService.refreshToken(loginUser);
//        }
        //TODO 根据小程序需要，返回需要数据
        ajax.put("user", user);
        ajax.put("permissions", permissions);
        //查询并返回企业相关信息
        GwEnterpriseInfo gwEnterpriseInfo = null;
        String enterpriseId = getUserEnterpriseId(loginUser);
        loginUser.setEnterpriseId(enterpriseId);
        if(StringUtils.isNotEmpty(loginUser.getEnterpriseId())){
           gwEnterpriseInfo = gwEnterpriseInfoService.selectGwEnterpriseInfoById(loginUser.getEnterpriseId());
        }
        ajax.put("enterpriseInfo", gwEnterpriseInfo);

        // 生成token
        String apiToken =  tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, apiToken);
        return ajax;
    }
    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 获取微信登录二维码
     * @return 结果
     **/
    public String wechatQrcode() throws UnsupportedEncodingException {
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        // 存入Redis，5分钟过期
        redisCache.setCacheObject("wechat_login_state:" + state, state, 5, TimeUnit.MINUTES);
        // 回调地址需URLEncode
        String redirectUri = URLEncoder.encode(loginCallBackUrl, StandardCharsets.UTF_8.name());
        String qrcodeUrl = String.format(
                "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect",
                pcAppId, redirectUri, state);

        return qrcodeUrl;
    }

    /**
     * 微信扫码登录
     * @param code
     * @param state
     * @return 集合
     **/
    public AjaxResult wechatLogin(String code, String state) {
        AjaxResult ajax = new AjaxResult();
        // 1. 验证state
        String cacheState = redisCache.getCacheObject("wechat_login_state:" + state);
        if (cacheState == null) {
            return AjaxResult.error(250,"扫码已过期，请重新登录");
        }

        // 2. 用code换openID
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                pcAppId,
                pcSecret,
                code
        );
        // 调用微信接口（若依自带HttpUtils工具类）
        String result = HttpUtils.sendGet(tokenUrl, param);
        JSONObject json = JSONObject.parseObject(result);
        String openId = json.getString("openid");
        if (openId == null) {
            return AjaxResult.error(251,"微信授权失败");
        }

        // 3. 检查openID是否已绑定
        SysUser  sysUser = userService.selectUserByPcOpenId(openId);
        if(sysUser==null){
            String bindState = UUID.randomUUID().toString();
            redisCache.setCacheObject("wechat_bind_state:" + bindState, openId, 10, TimeUnit.MINUTES);
            return AjaxResult.error(252,bindState);
        }

        LoginUser loginUser  = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        loginUser.setEnterpriseId(getUserEnterpriseId(loginUser));

        String apiToken =  tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, apiToken);

         return ajax;
    }

    /**
     * 微信绑定系统用户
     * @param state
     * @param phone
     * @return 结果
     **/
    public AjaxResult wechatBind(String state, String phone) {
        AjaxResult ajax = new AjaxResult();

        // 1. 获取openID
        String openId = redisCache.getCacheObject("wechat_bind_state:" + state);
        if (openId == null) {
            return AjaxResult.error(253,"绑定已过期，请重新扫码");
        }

        SysUser sysUser = iSysUserService.selectUserByPhone(phone);
        if(sysUser==null){
            return AjaxResult.error(254,"账号不存在");
        }
        if(StringUtils.isNotEmpty(sysUser.getPcOpenId()) && !sysUser.getPcOpenId().equals(openId)){
            return AjaxResult.error(254,"该账号已绑定其他微信");
        }
        //绑定
        sysUser.setPcOpenId(openId);
        iSysUserService.updateUser(sysUser);
        //绑定后直接登录
        LoginUser loginUser  = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        loginUser.setEnterpriseId(getUserEnterpriseId(loginUser));

        String apiToken =  tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, apiToken);

        return ajax;
    }
}
